﻿using Coldairarrow.Entity.Backstage.TheRules;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Backstage.TheRules
{
    public class BS_ReflectRuleBusiness : BaseBusiness<BS_ReflectRule>, IBS_ReflectRuleBusiness, ITransientDependency
    {
        readonly Operator _operator;
        public BS_ReflectRuleBusiness(IDbAccessor db, Operator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<BS_ReflectRule>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<BS_ReflectRule>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<BS_ReflectRule, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<BS_ReflectRule> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task<BS_ReflectRule> GetDataAsync()
        {
            BS_ReflectRule model = null;
            var list = await GetIQueryable().ToListAsync();
            if (list.Count > 0)
            {
                model = list[0];
            }

            return model;
        }

        public async Task AddDataAsync(BS_ReflectRule data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(BS_ReflectRule data)
        {
            //删除之前数据
            await UpdateAsync(x => !x.Id.Equals(data.Id),s => s.Deleted = true);

            data.Id = IdHelper.GetId();
            data.CreatorId = _operator.UserId;
            data.CreateTime = DateTime.Now;
            data.Deleted = false;
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            throw new BusException("此规则无法删除！");
        }

        #endregion

        #region 私有成员

        #endregion
    }
}